package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.service.CartService;
import csu.web.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class RemoveCartItemServlet extends HttpServlet {

    private static final String ERROR_FORM = "/WEB-INF/jsp/common/error.jsp";
    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    private String workingItemId;
    private Cart cart;

    private CartService cartService;

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        workingItemId = req.getParameter("workingItemId");

        HttpSession session = req.getSession();
        cart = (Cart) session.getAttribute("cart");
        Account account = (Account) session.getAttribute("account");
        Item item = cart.removeItemById(workingItemId);

        if (item == null){
            session.setAttribute("message","Attempted to remove null CartItem from Cart.");

            if(account != null) {
                String strUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                        + req.getContextPath() + req.getServletPath() + "?" + req.getQueryString();
                LogService logService = new LogService();
                String logInfo = logService.logInfo(" ") +"用户" +account.getUsername()+ "  " + "错误页面：购物车为空";
                logService.insertLogInfo(account.getUsername(),logInfo);
            }
            req.getRequestDispatcher(ERROR_FORM).forward(req,resp);
        }else{
            if(account != null) {
                cartService = new CartService();
                cartService.removeItem(account.getUsername(),workingItemId);
                LogService logService = new LogService();
                String logInfo = logService.logInfo(" ") +"用户" +account.getUsername()+ "  " + "移除商品"+workingItemId;
                logService.insertLogInfo(account.getUsername(),logInfo);
            }
            req.getRequestDispatcher(CART_FORM).forward(req,resp);
        }

    }
}
